<?php

namespace App\Console\Commands\OpenShop;

use App\Library\Rms\RmsShopApi;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Facades\Excel;

class LoadOrderAddress extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:load-order-address';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入开店门店选址地址';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '2048M');

        $url = $this->ask('请输入excel地址 : ');

        if (!$url) {
            $url = 'https://file.51kuafu.com/fb/60/6764dba7e9a33038dd1fbca67acd787905ef98fd0d3535862a24bb972f4b.xlsx';
        }

        // 获取在线文件内容
        $tempData = (new Client())->request("get", $url)->getBody()->getContents();

        // 重命名文件
        $fileName = 'php_import_' . md5($url) . '_' . date('YmdHis', time()) . "." . array_reverse(explode('.', $url))[0];

        // 文件存储的路径
        $savePath = sys_get_temp_dir() . '/' . $fileName;

        // 存文件
        file_put_contents($savePath, $tempData);

        Excel::import(new LoadOrderAddressToCollection(), $savePath);

        // 删除文件
        @unlink($savePath);
    }
}

class LoadOrderAddressToCollection implements ToCollection
{
    private string $errMsg = '';
    private int    $year   = 0;

    public function collection(Collection $collection)
    {
        // 校验列名
        $this->checkHeader($collection->first());
        if ($this->errMsg) {
            dd($this->errMsg);
        }

        $collection->map(function ($item, $row){
            $row = $row + 1;

            if ($row == 1) {
                return null;
            }
            // 常规内容校验
            list($orderNo, $provinceName, $cityName, $districtName, $address) = $item;
            //通过地区获得省市区code
            $areaData = (new RmsShopApi())->getAreaCodeByArea([$provinceName, $cityName, $districtName])['data'];
            $provinceCode = 0;
            $cityCode     = 0;
            $districtCode = 0;
            collect($areaData)->each(function ($item) use (&$provinceCode, &$cityCode, &$districtCode){
                if ($item['level'] == 1) {
                    $provinceCode = $item['code'];
                    return;
                }

                if ($item['level'] == 2) {
                    $cityCode = $item['code'];
                    return;
                }

                if ($item['level'] == 3) {
                    $districtCode = $item['code'];
                    return;
                }
            });

            if (!$provinceCode) {
                dump('订单-'. $orderNo . '-provinceCode获取异常-' . '行数:' . $row);
            }

            if (!$cityCode) {
                dump('订单-'. $orderNo . '-cityCode获取异常-' . '行数:' . $row);
            }

            if (!$districtCode) {
                dump('订单-'. $orderNo . '-districtCode获取异常-' . '行数:' . $row);
            }
            //入库操作
            //用户基础信息
            OpenShopUserBaseInfoModel::query()
                ->where('orderNo', $orderNo)
                ->update([
                    'shopProvinceCode'        => $provinceCode,
                    'shopCityCode'            => $cityCode,
                    'shopDistrictCode'        => $districtCode,
                    'shopAddressPrefix'       => $provinceName . '-' . $cityName . '-' . $districtName,
                    'shopAddress'             => $address,
                    'chooseShopProvinceCode'  => $provinceCode,
                    'chooseShopCityCode'      => $cityCode,
                    'chooseShopDistrictCode'  => $districtCode,
                    'chooseShopAddressPrefix' => $provinceName . '-' . $cityName . '-' . $districtName,
                ]);
            //选址主表
            OpenShopLocationModel::query()
                ->where('orderNo', $orderNo)
                ->update([
                    'shopAddressPrefix' => $provinceName . '-' . $cityName . '-' . $districtName,
                    'provinceCode'      => $provinceCode,
                    'cityCode'          => $cityCode,
                    'districtCode'      => $districtCode,
                    'shopDetailAddress' => $address,
                ]);
            //选址信息
            OpenShopSiteLocationModel::query()
                ->where('orderNo', $orderNo)
                ->whereIn('source',
                    [
                        OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                        OpenShopSiteLocationModel::SOURCE_HOUSING
                    ])
                ->update([
                    'chooseShopProvinceCode' => $provinceCode,
                    'cityArea'               => $provinceName . '-' . $cityName . '-' . $districtName,
                    'provinceCode'           => $provinceCode,
                    'cityCode'               => $cityCode,
                    'areaCode'               => $districtCode,
                    'address'                => $address,
                ]);
            //地址表
            OpenShopAddressModel::autoAdd($orderNo);
        })->filter();
    }

    private function checkHeader(Collection $item)
    {
        $formColumn = [
            "订单编号",
            "门店选址省份",
            "门店选址城市",
            "门店选址区县",
            "详细地址",
        ];

        foreach ($formColumn as $k => $v) {
            $dataV = $item[$k] ?? '';

            if (strpos($dataV, $v) === false) {
                $this->errMsg .= sprintf("第%d列，列名错误。应为：%s，传入：%s", $k + 1, $v, $dataV) . PHP_EOL;
            }
        }
    }

}
